import Skype4Py
from sendEmail import SkypeSendEmail
from pysqlite2 import dbapi2 as sqlite
from properties import Properties
import time

skype = Skype4Py.Skype()
skype.FriendlyName = 'Sync_chat_history'
skype.Attach()

chats = skype.Chats

con = sqlite.connect('skypesync')
p = Properties()
p.load(open('skype.properties'))
		

for c in chats:
    # c.Messages is a tuple, to be able to sort it,
    # convert it into a list
    msg_list = list(c.Messages)
    #dialogPartner=c.DialogPartner
    dialogPartner=''
    
    members=c.Members
    #my skype full name
    me=p['skypeFullName']
    
    for m in members:
	 partner=m.FullName
	 if partner != me:
		 dialogPartner=dialogPartner+' '+partner
    
    print dialogPartner
    # Sorting based on timestamps, with custom compare fct
    def message_timestamp_cmp(x, y):
        return int(x.Timestamp - y.Timestamp)
        # why are timestamps float and not int in Skype4Py?
    msg_list.sort(message_timestamp_cmp)
    cur = con.cursor()
    for m in msg_list:
	strId=str(m.Id)
	cur.execute('SELECT * FROM messages WHERE messageid="'+strId+'"')
	row=cur.fetchall()
	print row
	if len(row) != 0:
		continue
	
	messageIntro=m.Body[0:30]+'...'
	
	user=m.Sender
	username=user.FullName
	skypeEmail=SkypeSendEmail()
	dateTime=m.Datetime.isoformat(' ')
	body=m.Body
	
	flg=1	
	while flg==1:
		try:
			skypeEmail.send_email(dialogPartner, dateTime, messageIntro, body , username)
			flg=0
		except:
			time.sleep(20)
			
	cur.execute('INSERT INTO messages (messageid) VALUES("'+strId+'")')
	con.commit()	
	time.sleep(200)
